package com.urea.web.controller.urea.api;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaMessage;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMsgEvent;
import cn.binarywang.wx.miniapp.constant.WxMaConstants;
import com.google.common.collect.Lists;
import com.urea.common.core.controller.BaseController;
import com.urea.common.core.domain.AjaxResult;
import com.urea.common.core.redis.RedisCache;
import com.urea.common.exception.ServiceException;
import com.urea.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * 类描述: 小程序接收消息
 *
 * @author fangXu
 * @version 1.0
 * @date 2023/9/21 11:42
 */
@RestController
@RequestMapping("/mini")
@Slf4j
public class WxMiniController extends BaseController {

    @Autowired
    private  WxMaService wxMaService;
    @Autowired
    private RedisCache redisCache;

    /**
     * 微信公众号消息验证
     * @param signature 签名
     * @param timestamp 时间错
     * @param nonce nonce
     * @param echostr 随机串
     * @return 合法返回随机串
     */
    @GetMapping("/receiveMsg")
    public String msgController(@RequestParam("signature")String signature, @RequestParam("timestamp") String timestamp,
                                @RequestParam("nonce")String nonce, @RequestParam("echostr") String echostr){
        log.info("############接受到数据:{}##############",signature);
        boolean b = wxMaService.checkSignature(timestamp, nonce, signature);
        if (!b){
            throw new ServiceException("消息校验异常!");
        }else{
            log.info("##################消息合法###############");
        }
        return echostr;
    }

    /**
     * 接收小程序消息
     * @return 合法返回随机串
     */
    @PostMapping("/receiveMsg")
    public String post(@RequestBody String requestBody,
                       @RequestParam(name = "msg_signature", required = false) String msgSignature,
                       @RequestParam(name = "encrypt_type", required = false) String encryptType,
                       @RequestParam(name = "signature", required = false) String signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce) {
        log.info("\n接收微信请求：[msg_signature=[{}], encrypt_type=[{}], signature=[{}]," +
                        " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
                msgSignature, encryptType, signature, timestamp, nonce, requestBody);
        final boolean isJson = Objects.equals(wxMaService.getWxMaConfig().getMsgDataFormat(),
                WxMaConstants.MsgDataFormat.JSON);
        if (StringUtils.isBlank(encryptType)) {
            // 明文传输的消息
            WxMaMessage inMessage;
            if (isJson) {
                inMessage = WxMaMessage.fromJson(requestBody);
                WxMaSubscribeMsgEvent.SubscribeMsgPopupEvent popupEvents = inMessage.getUselessMsg().getPopupEvents();
                WxMaSubscribeMsgEvent.SubscribeMsgChangeEvent changeEvents = inMessage.getUselessMsg().getChangeEvents();
                WxMaSubscribeMsgEvent.SubscribeMsgSentEvent sentEvent = inMessage.getUselessMsg().getSentEvent();
                if (Objects.nonNull(popupEvents)){
                    List<WxMaSubscribeMsgEvent.PopupEvent> list = popupEvents.getList();
                    if (CollectionUtils.isNotEmpty(list)){
                        for (WxMaSubscribeMsgEvent.PopupEvent popupEvent : list) {
                            if ("accept".equals(popupEvent.getSubscribeStatusString())){
                                // 用户缓存到redis
                                redisCache.setCacheObject(popupEvent.getTemplateId().concat("@").concat(inMessage.getFromUser()),"1");
                            }else{
                                redisCache.deleteObject(popupEvent.getTemplateId().concat("@").concat(inMessage.getFromUser()));
                            }
                        }
                    }
                }else if (Objects.nonNull(changeEvents)){
                    List<WxMaSubscribeMsgEvent.ChangeEvent> list = changeEvents.getList();
                    if (CollectionUtils.isNotEmpty(list)){
                        for (WxMaSubscribeMsgEvent.ChangeEvent changeEvent : list) {
                            if ("reject".equals(changeEvent.getSubscribeStatusString())){
                                redisCache.deleteObject(changeEvent.getTemplateId().concat("@").concat(inMessage.getFromUser()));
                            }
                        }
                    }
                }else if (Objects.nonNull(sentEvent)){
                    WxMaSubscribeMsgEvent.SentEvent sent = sentEvent.getList();
                    if (Objects.nonNull(sent)){
                        // 0成功
                        log.info("##################消息模板:{},消息id:{},发送给用户:{},结果:{}###################################"
                        ,sent.getTemplateId(),sent.getMsgId(),inMessage.getFromUser(),sent.getErrorCode());
                    }
                }
            }
//            this.route(inMessage);
//            WxMaConfigHolder.remove();//清理ThreadLocal
        }
        return "success";
    }
}
